<template>
  <div class="app-container">
    <div class="detail-header">
      <el-page-header @back="goBack">
        <template #content>订单详情</template>
      </el-page-header>
    </div>

    <el-row :gutter="20" class="detail-content" v-loading="loading">
      <!-- 订单基本信息 -->
      <el-col :span="24">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>订单信息</span>
              <el-tag :type="statusFilter(orderInfo.status)">
                {{ statusTextFilter(orderInfo.status) }}
              </el-tag>
            </div>
          </template>
          <el-descriptions :column="3" border>
            <el-descriptions-item label="订单编号">
              {{ orderInfo.orderId }}
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">
              {{ orderInfo.createTime }}
            </el-descriptions-item>
            <el-descriptions-item label="订单金额">
              ¥{{ orderInfo.totalAmount?.toFixed(2) }}
            </el-descriptions-item>
            <el-descriptions-item label="支付方式">
              {{ orderInfo.paymentMethod }}
            </el-descriptions-item>
            <el-descriptions-item label="支付时间">
              {{ orderInfo.paymentTime }}
            </el-descriptions-item>
            <el-descriptions-item label="支付状态">
              {{ orderInfo.paymentStatus }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>

      <!-- 收货信息 -->
      <el-col :span="24" class="mt-20">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>收货信息</span>
            </div>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="收货人">
              {{ orderInfo.receiverName }}
            </el-descriptions-item>
            <el-descriptions-item label="联系电话">
              {{ orderInfo.receiverPhone }}
            </el-descriptions-item>
            <el-descriptions-item label="收货地址" :span="2">
              {{ orderInfo.receiverAddress }}
            </el-descriptions-item>
            <el-descriptions-item label="备注" :span="2">
              {{ orderInfo.remark || '无' }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>

      <!-- 商品信息 -->
      <el-col :span="24" class="mt-20">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>商品信息</span>
            </div>
          </template>
          <el-table :data="orderInfo.items" style="width: 100%">
            <el-table-column prop="goodsId" label="商品ID" width="180" />
            <el-table-column prop="goodsName" label="商品名称" />
            <el-table-column prop="price" label="单价">
              <template #default="scope">
                ¥{{ scope.row.price.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="100" />
            <el-table-column label="小计">
              <template #default="scope">
                ¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}
              </template>
            </el-table-column>
          </el-table>
          <div class="order-total">
            <span>订单总额：</span>
            <span class="price">¥{{ orderInfo.totalAmount?.toFixed(2) }}</span>
          </div>
        </el-card>
      </el-col>

      <!-- 订单状态记录 -->
      <el-col :span="24" class="mt-20">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>订单状态记录</span>
            </div>
          </template>
          <el-timeline>
            <el-timeline-item
              v-for="(activity, index) in orderInfo.statusHistory"
              :key="index"
              :timestamp="activity.time"
              :type="activity.type"
            >
              {{ activity.content }}
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>

      <!-- 操作按钮 -->
      <el-col :span="24" class="mt-20">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>订单操作</span>
            </div>
          </template>
          <div class="operation-buttons">
            <el-button
              v-if="orderInfo.status === 'pending'"
              type="primary"
              @click="handleConfirmOrder"
            >
              确认订单
            </el-button>
            <el-button
              v-if="orderInfo.status === 'pending'"
              type="danger"
              @click="handleCancelOrder"
            >
              取消订单
            </el-button>
            <el-button
              v-if="orderInfo.status === 'processing'"
              type="success"
              @click="handleCompleteOrder"
            >
              完成订单
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getOrderDetail, updateOrderStatus, cancelOrder } from '@/api/orders'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const orderInfo = ref({})

// 状态过滤器
const statusFilter = (status) => {
  const statusMap = {
    pending: 'warning',
    processing: 'primary',
    completed: 'success',
    cancelled: 'info'
  }
  return statusMap[status]
}

// 状态文本过滤器
const statusTextFilter = (status) => {
  const statusMap = {
    pending: '待处理',
    processing: '处理中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status]
}

// 获取订单详情
const getOrderInfo = async () => {
  try {
    loading.value = true
    const orderId = route.params.id
    const res = await getOrderDetail(orderId)
    orderInfo.value = res.data
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
  } finally {
    loading.value = false
  }
}

// 确认订单
const handleConfirmOrder = async () => {
  try {
    await ElMessageBox.confirm('确认要接受此订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await updateOrderStatus(orderInfo.value.orderId, 'processing')
    ElMessage.success('订单已确认')
    getOrderInfo()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认订单失败:', error)
      ElMessage.error('确认订单失败')
    }
  }
}

// 取消订单
const handleCancelOrder = async () => {
  try {
    await ElMessageBox.confirm('确认要取消此订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'danger'
    })
    
    await cancelOrder(orderInfo.value.orderId)
    ElMessage.success('订单已取消')
    getOrderInfo()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error('取消订单失败')
    }
  }
}

// 完成订单
const handleCompleteOrder = async () => {
  try {
    await ElMessageBox.confirm('确认要完成此订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'success'
    })
    
    await updateOrderStatus(orderInfo.value.orderId, 'completed')
    ElMessage.success('订单已完成')
    getOrderInfo()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('完成订单失败:', error)
      ElMessage.error('完成订单失败')
    }
  }
}

// 返回列表
const goBack = () => {
  router.push('/orders')
}

// 初始化
onMounted(() => {
  getOrderInfo()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.detail-header {
  margin-bottom: 20px;
}

.detail-content {
  margin-top: 20px;
}

.mt-20 {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-total {
  margin-top: 20px;
  text-align: right;
  padding-right: 20px;
}

.order-total .price {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
  margin-left: 10px;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
}
</style>